<?php

namespace App\Service\WorkOrder;

use App\Enums\WorkOrder\MissionEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Models\WorkOrder\WorkOrderApplyContentModel;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Models\WorkOrder\WorkOrderGatherModel;
use App\Support\CustomForm\AttributeWorkOrderSupport;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class WorkOrderBaseService
{
    //工单生成 生成规则: 开头字母标识 子类 时间 数量 3-4位   2+2+8+4 = 16


    const AUTOINCREMENT_REDIS_KEY = 'TIGER_WORK_ORDER_NO:';

    /**
     * 生成对应工单
     * @param $type //工单大类  具体看 OrderEnum 类
     * @param $child //工单子类  具体看 OrderEnum 类
     * @return string
     */
    public static function createWorkOrderNo($type, $child)
    {
        $prefix = OrderEnum::PROBLEM_PID_PREFIX_TEXT[$type] ?? OrderEnum::WORK_ORDER_PREFIX_ROLE;
        switch ($type) {
            case OrderEnum::PROBLEM_PID_1:
                $next = OrderEnum::PROBLEM_PID_1_CHILDREN_PREFIX[$child] ?? OrderEnum::WORK_ORDER_CHILD_PREFIX_ROLE;
                break;
            case OrderEnum::PROBLEM_PID_2:
                $next = OrderEnum::PROBLEM_PID_2_CHILDREN_PREFIX[$child] ?? OrderEnum::WORK_ORDER_CHILD_PREFIX_ROLE;
                break;
            case OrderEnum::PROBLEM_PID_5:
                $next = OrderEnum::FUNCTION_OPEN_CHILDREN_MAPPING[$child] ?? OrderEnum::WORK_ORDER_CHILD_PREFIX_ROLE;
                break;
            case OrderEnum::PROBLEM_PID_6:
                $next = OrderEnum::PROBLEM_PID_6_CHILDREN_PREFIX[$child] ?? OrderEnum::WORK_ORDER_CHILD_PREFIX_ROLE;
                break;
            case OrderEnum::PROBLEM_PID_7:
                $next = OrderEnum::PROBLEM_PID_7_CHILDREN_PREFIX[$child] ?? OrderEnum::WORK_ORDER_CHILD_PREFIX_ROLE;
                break;
            case OrderEnum::PROBLEM_PID_8:
                $next = OrderEnum::PROBLEM_PID_8_CHILDREN_PREFIX[$child] ?? OrderEnum::WORK_ORDER_CHILD_PREFIX_ROLE;
                break;
            case OrderEnum::PROBLEM_PID_9:
                $next = OrderEnum::PROBLEM_PID_9_CHILDREN_PREFIX[$child] ?? OrderEnum::WORK_ORDER_CHILD_PREFIX_ROLE;
                break;
            case OrderEnum::PROBLEM_PID_10:
                $next = OrderEnum::PROBLEM_PID_10_CHILDREN_PREFIX[$child] ?? OrderEnum::WORK_ORDER_CHILD_PREFIX_ROLE;
                break;
            default:
                $next = OrderEnum::WORK_ORDER_CHILD_PREFIX_ROLE;
        }
        $dateTime = date('YmdHis');
        $count    = str_pad(self::autoincrementByRedis($prefix . $next), 4, "0", STR_PAD_LEFT);
        return $prefix . $next . $dateTime . $count;
    }

    /**
     * 数量自增
     * @param $identification
     * @return mixed
     */
    public static function autoincrementByRedis($identification)
    {
        $key = sprintf(self::AUTOINCREMENT_REDIS_KEY . '%s:%s', date('Ymd'), $identification);

        $res = Redis::incr($key, 1);
        if ($res == 1) {
            Redis::expireAt($key, strtotime(date('Y-m-d')) + 86401);
        }
        return $res;
    }

    //初步创建工单以及工单详情
    public static function createWorkOrder(
        $shopId,
        $problemPid,
        $problemChildId,
        $problemDesc,
        $content,
        array $extra,
        bool $isBackend = false
    ): string {
        $workOrderNo = self::createWorkOrderNo($problemPid, $problemChildId);
        DB::beginTransaction();
        try {
            $originalContent = json_decode($content, true);
            //工单主表
            WorkOrderApplyMainModel::query()->create(array_merge([
                'workOrderNo'    => $workOrderNo,
                'shopId'         => $shopId,
                'problemPid'     => $problemPid,
                'problemChildId' => $problemChildId,
                'extra'          => json_encode($extra, JSON_UNESCAPED_UNICODE),
                'problemDesc'    => $problemDesc,
                'step'           => MissionEnum::STEP_1,
            ], $isBackend ? [
                "sourceType" => $originalContent["sourceType"],
                "createdAt"  => $originalContent["isCompleted"] ? time() : strtotime($originalContent["completeTime"])
            ] : []));

            //工单详情
            WorkOrderApplyContentModel::query()->create([
                'workOrderNo' => $workOrderNo,
                'content'     => $content,
            ]);

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::info('创建工单失败 读取工单号:' . $workOrderNo);
            throw new \Exception('添加工单失败');
        }

        return $workOrderNo;
    }


    //生成新的单个表单
    public static function singleFormBuild($inputName, $inputType, $inputDesc)
    {
        return AttributeWorkOrderSupport::getInstance($inputName, $inputType, $inputDesc);
    }

    /**
     * 同步 workOrderGather
     * @param string $workOrderNo
     * @param int $shopId
     * @return void
     */
    public static function syncWorkOrderGather(string $workOrderNo, int $shopId)
    {
        WorkOrderGatherModel::query()
            ->updateOrCreate([
                'workOrderNo' => $workOrderNo,
                'shopId'      => $shopId
            ]);
    }

}
